<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="login-title">酒店管理系统登录</h2>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onLogin" :loading="loading" style="width:100%">登录</el-button>
        </el-form-item>
        <div class="register-link">
          没有账号？<el-link type="primary" @click="goToRegister">去注册</el-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login, getCurrentUser } from '@/api/user'
import { useUserInfoStore } from '@/stores/userInfo'
import type { FormRules } from 'element-plus'

const router = useRouter()
const userInfoStore = useUserInfoStore() as any

// 页面加载时检查当前用户状态
onMounted(() => {
  console.log('当前存储的用户信息:', userInfoStore.userInfo)
})

const formRef = ref()
const form = reactive({
  email: '',
  password: ''
})
const rules: FormRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}
const loading = ref(false)

// 检查用户是否有特定权限
const hasPermission = (permissions: any[], permissionName: string) => {
  return permissions.some((permission: any) => {
    // 如果permission是字符串，直接比较
    if (typeof permission === 'string') {
      return permission === permissionName;
    }
    
    // 尝试从对象中获取权限名称
    const permissionCode = permission.name || 
                           permission.permission_name || 
                           permission.permissionName || 
                           permission.code ||
                           '';
    
    // 如果是完全匹配
    if (permissionCode === permissionName) {
      return true;
    }
    
    // 如果数据库存储的是ID而不是权限名称，需要额外判断
    if (permission.id) {
      // 根据数据库中的权限ID表映射关系判断
      const permissionIdMap = {
        1: 'view_hotel',
        2: 'view_room',
        3: 'view_review',
        4: 'create_review',
        5: 'create_order',
        6: 'pay_order',
        7: 'cancel_order',
        8: 'create_hotel',
        9: 'create_room',
        10: 'update_room',
        11: 'update_hotel',
        12: 'admin_manage'
      };
      
      return permissionIdMap[permission.id] === permissionName;
    }
    
    return false;
  });
}

const goToRegister = () => {
  router.push('/register')
}

const onLogin = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) return
    loading.value = true
    console.log('发送登录请求...')
    
    login({ email: form.email, password: form.password }).then((res: any) => {
      // axios返回的res结构：{ data: { code, data, msg, ... } }
      const result = res.data
      console.log('登录响应:', result)
      
      if (result.code === 200 && result.data) {
        console.log('登录成功，准备获取当前用户信息...')
        
        // 登录成功后调用getCurrentUser获取完整用户信息
        getCurrentUser().then((userRes: any) => {
          console.log('getCurrentUser 原始响应:', userRes)
          
          const userResult = userRes.data
          console.log('获取当前用户信息:', userResult)
          
          if (userResult.code === 200 && userResult.data) {
            console.log('当前用户信息数据结构:', JSON.stringify(userResult.data))
            
            // 直接存储后端返回的完整用户信息结构
            userInfoStore.setUserInfo(userResult.data)
            
            // 存储后再次检查
            console.log('存储后的用户信息:', userInfoStore.userInfo)
            
            // 根据用户类型决定跳转页面
            if (userInfoStore.isAdmin()) {
              // 管理员跳转到用户管理页面
              router.push('/user');
            } else if (userInfoStore.isHotelOwner()) {
              // 酒店商家跳转到酒店管理页面
                router.push('/hotel');
            } else {
              // 普通用户跳转到酒店列表页面
              router.push('/hotel');
            }
            
            ElMessage.success('登录成功')
          } else {
            ElMessage.error(userResult.msg || userResult.message || '获取用户信息失败')
          }
          loading.value = false
        }).catch((error) => {
          console.error('获取用户信息错误:', error)
          loading.value = false
          ElMessage.error('获取用户信息失败')
        })
      } else {
        loading.value = false
        ElMessage.error(result.msg || result.message || '登录失败')
      }
    }).catch((error) => {
      console.error('登录错误:', error)
      loading.value = false
      ElMessage.error('登录失败')
    })
  })
}
</script>
<style scoped>
.login-container {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f9f6f2;
  z-index: 10;
}
.login-card {
  width: 400px;
  padding: 40px 30px 20px 30px;
}
.login-title {
  text-align: center;
  margin-bottom: 30px;
}
.register-link {
  text-align: center;
  margin-top: 15px;
}
</style>
